var tgd = tgd || {};
tgd.Media = tgd.Media || {};


tgd.Media.Library = function (ID, Name) {

    var db;

    db = openDatabase("MediaLibrary", "1.0", "Maverick Mindless Drones - Media Library", 5 * 1024 * 1024);

    var _id = ID.toString();  //todo: worry about type sometime.
    var _name = Name.toString();
    var _entries = [];

    this.getID = function() {
        return _id;
    }

    this.getName = function() {
        return _name;
    }

    this.setName = function(val) {
        return _name = val;
    }

    this.getEntries = function() {
        return _entries;  //todo: don't return native data, right?
    }
    
    //should this save the entry to the database?  or should entry.save() do that?
    this.addEntry = function(entry, callback) {
        _entries.push(entry);  //todo: this may be a hack, should I check for uniqueness?
        entry.setLibraryID(_id);
        db.transaction(function(t) {
            t.executeSql("SELECT UPC FROM entry WHERE UPC = ?", [entry.getUPC()], function(t, data1) {
                if (data1.rows.length == 0) {
                    db.transaction(
                        function(t2) {
                            t2.executeSql("INSERT INTO entry (UPC, LibraryID, Name, ThumbURL, NameSource) values (?, ?, ?, ?, ?)",
                                [entry.getUPC(), _id, entry.getName(), entry.getThumbURL(), entry.getNameSource()],
                                function(t3, data2) {
                                    callback({ Status : 1, Message : "Inserted new UPC [" + entry.getUPC() + "] into library [" + _id + "]." });
                                }, function(t3, data2) {
                                    callback({ Status : 0, Message : "Error inserting UPC [" + entry.getUPC() + "] into library [" + _id + "].  " + data2.message })
                                });
                        }
                    );
                } else {
                    callback({ Status : 0, Message : "UPC already exists." });  //todo: make error/success statuses an enum
                }
            });
        });
    }
    
    this.save = function(callback) {
        var self = this;
        db.transaction(
            function(t) {
                t.executeSql("UPDATE library SET Name = ? WHERE ID = ?",
                    [_name, _id],
                    function(t, results) {
                        callback({ Status : 1, Message : "Library saved.", Library : self });
                    },
                    function(t, error) {
                        callback({ Status : 0, Message : error.message, Library : self });
                    }
                );
            }
        );
    }
}
